package rabbitmq;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import rabbitmq.model.User;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 消息生成者
 * Virtual Hosts queue
 * 一个用户可以对应多个Virtual Hosts，一个Virtual Hosts可以创建多个queue，过个Virtual Hosts之间相互独立
 * fanout:广播到同一exchange下所有队列，此事RoutingKey的设置不起作用
 * direct:发送消息到同一exchange下拥有相同routing_key下的所有队列
 */
public class Producer {

	@Test
	public void producerTest() {
		Connection connection = null;
		Channel channel = null;
		try {
			ConnectionService conn = new ConnectionService();
			//创建与RabbitMQ服务器的TCP连接
			connection = conn.initConn();
			channel = connection.createChannel();

			//所有队列发送相同的内容，设置exchange持久化，durable=true，设置exchange及对应的类型
			channel.exchangeDeclare("test_exchange", "fanout", true, false, null);
			/**声明队列，如果队列已存在，则直接写入durable=true 设置队列持久化,fanout 不用申明队列*/
			//channel.queueDeclare("firstQueue", true, false, false, null);
			//绑定路由和队列
			//channel.queueBind("firstQueue", "test_exchange", "test_routing_key", null);
			String message ;

			long startTime = System.currentTimeMillis();
			for (int i = 0; i <1000 ; i++) {
				User user = new User();
				user.setId(i+1);
				user.setName("Hubert"+(i+1));
				user.setSex(i+1);
				message = JSON.toJSONString(user);
				//exchange在fanout类型下，设置routing_key为空，即不指明key,不能设置为null，设置exchange即可,
				channel.basicPublish("test_exchange", "", null, message.getBytes("UTF-8"));
				System.out.println("Send Message is:'" + message + "'");
			}
//			System.out.println(System.currentTimeMillis() - startTime);
		} catch(Exception ex) {
			ex.printStackTrace();
		} finally {
			if(channel != null) {
				try {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (TimeoutException e) {
					e.printStackTrace();
				}
			}
			if(connection != null) {
				try {
					connection.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
